<?php
/**
 * Created by PhpStorm.
 * Author: sitenv@aliyun.com
 * CreateTime: 2021/07/09 17:46
 * Blog：www.myblogs.xyz
 */

namespace app\common\model;


class ActiveUser extends Common
{
    protected $name = 'active_user';
    protected $pk = 'active_id';

    // 记录用户日活数据
    public function insertActive($member_id = 0)
    {
        // 获取用户注册时间
        $member_model = new Member();
        $member_data = $member_model->getFind($member_id, 'create_time,last_time');
        if (!empty($member_data))
        {
            // 获取当前注册用户数量
            $member_number = $member_model->getCount(['status'=>0]);
            // 当前时间信息
            $last_time = $member_data['last_time'];
            $beg_time = strtotime(date('Y-m-d', NEW_TIME) . ' 00:00:00');
            // 检测是否创建记录
            if (!$this->getExists(['create_time'=>$beg_time]))
            {
                $this->insert(['member_number'=>$member_number,'create_time'=>$beg_time]);
            }
            // 新用户
            if (empty($last_time))
            {
                $this->setInc(['create_time'=>$beg_time], 'register_number');
                $this->setInc(['create_time'=>$beg_time], 'member_number');
            }
            // 今日登录
            if ($last_time < $beg_time)
            {
                $this->setInc(['create_time'=>$beg_time], 'login_number');
            }
        }
    }

    // 组合数据日活
    public function getActive($limit = 15)
    {
        $xAxis = [];
        $login = [];
        $register = [];
        for ($i = $limit; $i > 0; $i--){
            $s = $i - 1;
            $xAxis[] = strtotime('-' . $s . ' day');
        }
        if (!empty($xAxis)) {
            if (is_array($xAxis)){
                foreach ($xAxis as $key => &$val) {
                    $create_time = strtotime(date('Y-m-d', $val) . ' 00:00:00');
                    $val = date('m-d', $val);
                    $active_data = $this->getFind(['create_time'=>$create_time]);
                    $login[] = empty($active_data['login_number']) ? 0 : intval($active_data['login_number']);
                    $register[] = empty($active_data['register_number']) ? 0 : intval($active_data['register_number']);
                }
            }
        }
        $data = [
            'xAxis'=>json_encode($xAxis),
            'login'=>json_encode($login),
            'register'=>json_encode($register)
        ];
        return $data;
    }

}